package com.ruoyi.aitmsdz.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.aitcommon.anotation.AitFlow;
import com.ruoyi.aitcommon.anotation.ServiceLog;
import com.ruoyi.aitcommon.service.FlowService;
import com.ruoyi.aitcommon.utils.FlowUtils;

@Service
public class MsdzService {
	@Autowired
	FlowService flowService;
	
	public Object dataSync(String path) throws Exception {
//		构造参数
		return flowService.templateService(path);
	}
	
	@AitFlow("flow并发测试")
	public String test() throws InterruptedException {
		System.out.println("线程名称:"+Thread.currentThread().getName()+" 开始");
		Thread.sleep(3000);
		System.out.println("线程名称:"+Thread.currentThread().getName()+" 结束");
		return FlowUtils.getFlowName()+":"+FlowUtils.getFlowID();
	}
	
	/**
	 * 将NC附件信息转换为H5格式
	 * @param datas nc返回附件信息
	 * @param codeField nc单据业务主键
	 * @param attField nc单据H5存储字段
	 * @return
	 */
	@ServiceLog("nc单据附件地址更新")
	public List<Map<String,Object>> getAttachmentH5(List<Map<String,Object>> datas,
			String host,String codeField,String attField){
		Map<String,Object> doclist=new LinkedHashMap<String,Object>();
		
//		附件信息按照单号分组
		for(Map<String,Object> data:datas) {
			if(data.get("docno")==null) continue;
			
			String docno=data.get("docno").toString();
			
			if(doclist.containsKey(docno)) {
				List<Object> attachments = (List<Object>)doclist.get(docno);
				attachments.add(data);
			}else {
				List<Object> attachments = new ArrayList<Object>();
				attachments.add(data);
				doclist.put(docno, attachments);
			}
		}
		
//		增对每张单构造附件H5
		List<Map<String,Object>> dochtmls=new ArrayList<Map<String,Object>>();
		for(String key:doclist.keySet()) {
			List<Object> attachments = (List<Object>)doclist.get(key);
			StringBuilder htmls=new StringBuilder();
			
			String docno=key;
			for(Object obj:attachments) {
				Map<String,Object> attachment=(Map<String,Object>)obj;
				String filepath1=attachment.get("filepath1").toString();
				String filename=attachment.get("FileName").toString();
				String url=host+"\\"+filepath1;
				String html="<a href=\"%s\" target=\"_blank\">%s</a>";
				html=String.format(html, url,filename);
				htmls.append(html);
			}
//			htmls.append("<p>附件点击打开</p>");
			
			Map<String,Object> dochtml=new LinkedHashMap<String,Object>();
			dochtml.put(codeField, docno);
			dochtml.put(attField, htmls.toString());
		}
		
		return dochtmls;
	}
}
